package com.hzhc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.entity.ChargeContract;
import com.hzhc.entity.ChargeContractDetail;
import com.hzhc.entity.ChargeContractFile;
import com.hzhc.mapper.ChargeContractMapper;
import com.hzhc.service.ChargeContractDetailService;
import com.hzhc.service.ChargeContractFileService;
import com.hzhc.service.ChargeContractService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.vo.ChargeContractVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>
 * 计费合同 服务实现类
 * </p>
 *
 * @author 1
 * @since 2024-05-28
 */
@Service
@RequiredArgsConstructor
public class ChargeContractServiceImpl extends ServiceImpl<ChargeContractMapper, ChargeContract> implements ChargeContractService {

    private final ChargeContractDetailService contractDetailService;
    private final ChargeContractFileService contractFileService;
//    private final ChargeContractFileMapper contractFileMapper;

    @Override
    public List<ChargeContractVo> getChargeContractList(Page<ChargeContractVo> page, ChargeContractVo vo) {
        IPage<ChargeContractVo> iPage = baseMapper.getChargeContractList(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> addChargeContract(ChargeContractVo vo,String contractFileUploadFolder,String contractFileAccessPath) {
        ChargeContract contract = new ChargeContract();
        BeanUtils.copyProperties(vo,contract);
        //save 合同主表
        boolean b = save(contract);
        //根据合同编号(唯一)找到该合同
        ChargeContract one = baseMapper.selectOne(new LambdaQueryWrapper<ChargeContract>()
                .eq(ChargeContract::getContractNo, contract.getContractNo()).eq(ChargeContract::getDisable,0));
        //detail表
        if (contract.getCopyContract()!=null){
            List<ChargeContractDetail> detailList = contractDetailService.list(new LambdaQueryWrapper<ChargeContractDetail>()
                    .eq(ChargeContractDetail::getContractId, contract.getCopyContractId())
                    .eq(ChargeContractDetail::getDisable, 0));

            detailList.forEach(s->s.setContractId(one.getId()));
             b = contractDetailService.saveBatch(detailList);
        }

        //合同附件表
        if (vo.getFile()!=null){
            for (MultipartFile file : vo.getFile()) {
                saveFiles(one,file,contractFileUploadFolder,contractFileAccessPath);
            }

        }

        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> updateChargeContract(ChargeContractVo vo,String contractFileUploadFolder,String contractFileAccessPath) {
        ChargeContract contract  = new ChargeContract();
        BeanUtils.copyProperties(vo,contract);
        boolean b = updateById(contract);

        //合同附件表
        if (vo.getFile()!=null){
            for (MultipartFile file : vo.getFile()) {
                saveFiles(contract,file,contractFileUploadFolder,contractFileAccessPath);
            }
        }
        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> delChargeContract(Long id) {
        ChargeContract contract = getById(id);
        contract.setDisable(true);
        contract.setUpdateTime(LocalDateTime.now());
        if (updateById(contract)){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public Boolean checkContractNo(ChargeContract contract) {
        LambdaQueryWrapper<ChargeContract> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChargeContract::getDisable,0)
                .eq(ChargeContract::getContractNo,contract.getContractNo());
        if (contract.getId()!=null){
            wrapper.ne(ChargeContract::getId,contract.getId());
        }
        int num = count(wrapper);
        return num <=0;
    }

    @Override
    public List<ChargeContractVo> getYzsChargeContractList(Page<ChargeContractVo> page, ChargeContractVo vo) {
        IPage<ChargeContractVo> iPage = baseMapper.getYzsChargeContractList(page,vo);
        return iPage.getRecords();
    }

    public void saveFiles(ChargeContract contract, MultipartFile files, String upfolder, String accessPath ){
        //设置日期格式
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //当地日期转换
        String dayFormat = LocalDate.now().format(formatters);
        //创建新文件：通过路径和时间
        File folder = new File(upfolder + File.separator + dayFormat);
        //文件是否存在，不存在进行创建。
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //获取文件名
        String regEx1 = "[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        String fileName = files.getOriginalFilename();
        String urlName=(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))+ Pattern.compile(regEx1).matcher(fileName).replaceAll("").trim());
        //设置路径
        String path = folder + File.separator;
        File file = getFileByName(1, path, urlName);
        try {
            // 上传文件到服务器
            files.transferTo(file);
            ChargeContractFile contractFile = new ChargeContractFile();
            contractFile.setFileName(files.getOriginalFilename());
            contractFile.setNewFileName(urlName);
            contractFile.setUserId(contract.getUserId());
            contractFile.setFileSize((double) (file.length() / 1024));
            contractFile.setCreateTime(LocalDateTime.now());
            contractFile.setFilePath(accessPath.substring(0, accessPath.lastIndexOf("/")) + "/" + dayFormat+"/"+file.getName());
            contractFile.setContractId(contract.getId().intValue());
            contractFileService.save(contractFile);
//            contractFileMapper.insert(contractFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取附件名称
    private File getFileByName(int count, String path, String fileName) {
        File file = new File(path + fileName);
        if (file.exists()) {
            // 文件名已存在
            String prefix = fileName.substring(0, fileName.lastIndexOf(".")) + "(" + count + ")";
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            file = getFileByName(count + 1, path, prefix + suffixName);
        }
        return file;
    }
}
